/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//package klientgui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

/**
 *
 * @author Kuba
 */
public class ClientJFrame extends javax.swing.JFrame{
    static final int POBIERZ = 0;
    static final int DODAJ = 1;
    static final int USUN = 2;
    static final int MODYFIKUJ = 3;

    /**
     * Creates new form ClientJFrame
     */
    public ClientJFrame() {
        initComponents();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        keyLabel = new javax.swing.JLabel();
        keyTextField = new javax.swing.JTextField();
        valueTextField = new javax.swing.JTextField();
        valueLabel = new javax.swing.JLabel();
        doButton = new javax.swing.JButton();
        actionComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        keyLabel.setText("Klucz");

        keyTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                keyTextFieldActionPerformed(evt);
            }
        });

        valueTextField.setEnabled(false);
        valueTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                valueTextFieldActionPerformed(evt);
            }
        });

        valueLabel.setText("Wartość");

        doButton.setText("Wykonaj");
        doButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(final java.awt.event.ActionEvent evt) {  
                (new Thread(new Runnable() {
					@Override
					public void run() {
						doButtonActionPerformed(evt);
						
					}
				})).start();
            }
        });

        actionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pobierz", "Dodaj", "Usuń", "Modyfikuj" }));
        actionComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	actionComboBoxActionPerformed(evt);
            }
        });
        
        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);



        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(keyLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(keyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(valueTextField)
                    .addComponent(valueLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(actionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(doButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(182, Short.MAX_VALUE))
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(valueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(doButton)
                    .addComponent(actionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(valueLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(keyLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(79, 79, 79)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void keyTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keyTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_keyTextFieldActionPerformed

    private void valueTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_valueTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_valueTextFieldActionPerformed

    private void doButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doButtonActionPerformed
                    String str;
                    String value;
                    String wartosc = "";
                    LinkedList<Integer> porty = new LinkedList<Integer>();
                    int type;
        switch (actionComboBox.getSelectedIndex()){
                case POBIERZ:
                    type = 1;
                    jTextArea1.append("Pobieranie...\n");
                    str = keyTextField.getText();
					porty = getServerID(str, type);    //narazie zakladam, ze jeden port
				    value = null;
                    for (int i=0; i < porty.size(); i++) {
                    wartosc = sendToClient(porty.get(i), str, type, value);
                    }
                    jTextArea1.append("Dla klucza: " + str + " wartosc wynosi: " + wartosc + "\n");

                    //@TODO 
                    break;
                case DODAJ:
                    type = 2;
                    jTextArea1.append("Dodawanie...\n");
                    str = keyTextField.getText();
                    value = valueTextField.getText();
                    porty = getServerID(str, type);
                    if (porty != null) {
                        for (int i=0; i < porty.size(); i++) {
                            sendToClient(porty.get(i), str, type, value);
                        }
                    }
                    //@TODO 
                    break;
                case USUN:
                    type = 4;
                    jTextArea1.append("Usuwanie...\n");
                    str = keyTextField.getText();
                    value = valueTextField.getText();
                    porty = getServerID(str, type);

                    for (int i=0; i < porty.size(); i++) {
                      sendToClient(porty.get(i), str, type, value);
                    }
                    //@TODO 
                    break;
                case MODYFIKUJ:
                    type = 3;
                    jTextArea1.append("Modyfikowanie...\n");
                    str = keyTextField.getText();
                    value = valueTextField.getText();
                    porty = getServerID(str, type);
                    for (int i=0; i < porty.size(); i++) {
                         sendToClient(porty.get(i), str, type, value);
                    }
                    //@TODO 
                    break;
            }
    }//GEN-LAST:event_doButtonActionPerformed

    private LinkedList<Integer> getServerID(String key, int typ) {
        Klientobsluga a = new Klientobsluga(5000) ;
        Message m = new Message() ;
        LinkedList<Integer> porty = new LinkedList<Integer>();
        int klucz = Integer.parseInt(key);
        m.setCommand("GET") ;

        m.setKey(klucz);
        m.setType(typ);
//        Thread t = new Thread(new Runnable() {
//            public void run() {
            	a.sendMessage(m);
            	m = a.getMessage() ; 
               

                if ( m.getType() == 10 ) {
                    System.out.println("Juz taki rekord zostal dodany");
                    return null;
                }
                else if (m.getType() == 11 ) {
                    System.out.println("Nie mozemy robic operacji na nieistniejacym rekordzie");
                    return null;
                }
                else
                 {
                    porty = m.getPorty();
               
//            }
//        });
        
        for (int i=0; i<porty.size(); i++){
            System.out.println(porty.get(i));
        }
               a.connectionClose() ;  
        return porty; 
        }
    }

    private String sendToClient(int port, String str, int type, String value) {
        try {
        Klientobsluga a = new Klientobsluga(port) ;
        Message m = new Message();
        int klucz = Integer.parseInt(str);  //zamieniam string str na int
        m.setKey(klucz);
        m.setType(type);
 
        if (type != 1) { // if not GET
            m.setCommand(value);
        }

            a.sendMessage(m);
            value = "";
            if (type == 1) {
                m = a.getMessage();    //zwraca wiadomosc ze wykonano
                System.out.println("Serwer BD na porcie " + port + " zwrocil mi wiadomosc " + m.getCommand()) ;
                value = m.getCommand();
            }

            a.connectionClose() ;
        }
        catch (Exception e) {
            System.out.println("serwer wylaczony");
        }
        return value;
    }
    
    private void actionComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
    	switch (actionComboBox.getSelectedIndex()){
	        case POBIERZ:
	            valueTextField.setEnabled(false);
	            break;
	        case DODAJ:
	            valueTextField.setEnabled(true);
	            break;
	        case USUN:
	            valueTextField.setEnabled(false);
	            break;
	        case MODYFIKUJ:
	            valueTextField.setEnabled(true);
	            break;
    	}
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox actionComboBox;
    private javax.swing.JButton doButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel keyLabel;
    private javax.swing.JTextField keyTextField;
    private javax.swing.JLabel valueLabel;
    private javax.swing.JTextField valueTextField;
    // End of variables declaration//GEN-END:variables

    public void createAndShow(){
    	try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientJFrame().setVisible(true);
            }
        });
    }
}
